package com.bawei.module_mine.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bawei.lib_common.base.BaseApplication
import com.bawei.module_mine.R
import com.bawei.module_mine.model.MineServiceModel
import com.bawei.module_mine.model.ServiceStatisticsModel

class MineAdapter(
    private val onApplyforItemClick: (() -> Unit)? = null,
    private val onAuditItemClick: (() -> Unit)? = null
): RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    companion object {
        const val TYPE_HEADER_FUNCTION = 0 //常用功能
        private const val TYPE_FUNCTION = 1  // 功能项
        const val TYPE_HEADER_STATISTICS = 3 // 服务统计
        private const val TYPE_STATS = 4     // 统计项
    }
    private val functionItems= mutableListOf<MineServiceModel>()
    private val stats= mutableListOf<ServiceStatisticsModel> ()
    fun setFunctionData(data:List<MineServiceModel>){
        functionItems.clear()
        functionItems.addAll(data)
        notifyDataSetChanged()
    }
    fun setStatisticsData(data:List<ServiceStatisticsModel>){
        stats.clear()
        stats.addAll(data)  //
        notifyDataSetChanged()
    }

    // 根据位置返回视图类型
    override fun getItemViewType(position: Int): Int {
        // 统计项的位置固定为功能项数量（仅当统计项存在时）
        return when {
            position == 0 -> TYPE_HEADER_FUNCTION // 第一个位置是常用功能标题
            position <= functionItems.size -> TYPE_FUNCTION // 功能项（位置1到functionItems.size）
            position == functionItems.size + 1 -> TYPE_HEADER_STATISTICS // 服务统计标题
            else -> TYPE_STATS // 统计项（位置大于functionItems.size+1）
        }
    }

    // 创建ViewHolder
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            TYPE_FUNCTION -> {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item_function, parent, false)
                FunctionViewHolder(view)
            }
            TYPE_STATS -> {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item_stats, parent, false)
                StatsViewHolder(view)
            }
            TYPE_HEADER_FUNCTION -> {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item_mine_function, parent, false)
                TitleViewHolder(view)
            }
            TYPE_HEADER_STATISTICS -> {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item_mine_statistics, parent, false)
                TitleViewHolder(view)
            }
            else -> throw IllegalArgumentException("未知的视图类型")
        }
    }

    // 绑定数据到ViewHolder
    @SuppressLint("ResourceAsColor")
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is TitleViewHolder -> {

            }
            is FunctionViewHolder -> {
                val item = functionItems[position-1]
                holder.icon.setImageResource(item.img)
                holder.name.text = item.text
                holder.icon.setOnClickListener {
                    when(item.id){
                        0 -> onApplyforItemClick?.invoke()
                        1 -> onAuditItemClick?.invoke()
                    }
                }
            }
            is StatsViewHolder -> {
                val statsPosition = position - (functionItems.size + 2)  // 计算统计项在 stats 中的实际索引
                if (statsPosition < 0 || statsPosition >= stats.size) {
                    // 防止越界（理论上不会触发）
                    return
                }
                val item = stats[statsPosition]  // 根据实际索引获取数据
                // 绑定统计数据（示例）
                holder.repairCount.text = item.message
                holder.processingRate.text = item.text
                // 根据id设置颜色（使用 ContextCompat 兼容不同API）
                val colorRes = when (item.id) {
                    0 -> com.bawei.lib_common.R.color.color_2f62c7
                    1 -> com.bawei.lib_common.R.color.color_40b223
                    2 -> com.bawei.lib_common.R.color.color_yellow_dark
                    else -> android.R.color.black // 默认颜色
                }
                holder.repairCount.setTextColor(ContextCompat.getColor(BaseApplication.instance, colorRes))
            }
        }
    }

    // 获取总条目数（功能项 + 统计项）
    override fun getItemCount(): Int = functionItems.size + stats.size + 2

    // 功能项ViewHolder
    class FunctionViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val icon: ImageView = view.findViewById(R.id.iv_icon)
        val name: TextView = view.findViewById(R.id.tv_name)
    }
    // 标题ViewHolder
    class TitleViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    }

    // 统计项ViewHolder
    class StatsViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val repairCount: TextView = view.findViewById(R.id.tv_repair_count)
        val processingRate: TextView = view.findViewById(R.id.tv_processing_rate)
    }

    // 配置LayoutManager的关键方法：设置不同视图类型的跨度大小
    fun setupLayoutManager(recyclerView: RecyclerView) {
        val layoutManager = GridLayoutManager(recyclerView.context, 3)
        layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return when (getItemViewType(position)) {
                    TYPE_HEADER_STATISTICS->3
                    TYPE_HEADER_FUNCTION->3
                    TYPE_STATS -> 1 // 统计项占据整行（4列）
                    else -> 1   // 功能项占据半行（1列）
                }
            }
        }
        recyclerView.layoutManager = layoutManager
        // 添加间距装饰（水平间距16dp，垂直间距8dp）
        val spacing = recyclerView.context.resources.getDimensionPixelSize(R.dimen.grid_spacing)
        recyclerView.addItemDecoration(GridSpaceItemDecoration(
            horizontalSpacing = spacing,  // 水平间距（左右）
            verticalSpacing = spacing / 2 // 垂直间距（上下，可根据需求调整）
        ))
        // 可选：启用预加载（提升滑动流畅性）
        recyclerView.setItemViewCacheSize(20)
    }
}
